<template>
  <el-dialog
    v-model="dialogVisible"
    :title="paramsData.id ? '编辑用户' : '添加用户'"
    width="30%"
    :before-close="cancel"
  >
    <el-form label-width="110px" ref="form" :model="paramsData" :rules="rules">
      <el-form-item label="职位名称" prop="roleName">
        <el-input
          v-model="paramsData.roleName"
          placeholder="请你输入职位名称"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveRole($parent)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { roleObj } from '@/api/acl/role/type'
import { addOrUpdateRole } from '@/api/acl/role'
import { ElMessage } from 'element-plus'
const dialogVisible = ref(false)
const paramsData = reactive<roleObj>({
  id: 0,
  roleName: '',
})

const cancel = () => {
  dialogVisible.value = false
  form.value?.resetFields()
  Object.assign(paramsData, {
    id: 0,
    roleName: '',
  })
}
const saveRole = async ($parent: any) => {
  await form.value.validate()
  const res: any = await addOrUpdateRole(paramsData)
  if (res.code === 200) {
    ElMessage.success(paramsData.id ? '更新成功' : '添加成功')
    paramsData.id || ($parent.pageNo = 1)
    cancel()
    $parent.getRoleList()
  }
}
// 点击添加
const addDialog = () => {
  dialogVisible.value = true
}
// 点击更新
const updateDialog = (row: roleObj) => {
  Object.assign(paramsData, row)
  dialogVisible.value = true
}
defineExpose({
  addDialog,
  updateDialog,
})
const validatorRoleName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length > 2 && value.trim().length < 6) return callBack()
  callBack(new Error('用户姓名必须2-6位'))
}
const form = ref()
const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
}
</script>
<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
